// pages/xctask/submit.js
const util = require('../../utils/util.js');
const apiUrl = require('../../utils/apiUrl.js');
var http = require('../../utils/httpHelper.js');
Page({
  /**
   * 页面的初始数据
   */
  data: {
    taskTitle: "",
    taskId: 0,
    loaddinghidden: true,
    formats: {},
    readOnly: false,
    keyboardHeight: 0,
    isIOS: false,
    showLoading: false,
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this

    var taskId = options.task_id;
    if (taskId) {
      that.setData({
        taskId: taskId
      })
    }
    var taskTitle = options.task_title;
    if (taskTitle) {
      that.setData({
        taskTitle: taskTitle
      })
    }
    const platform = wx.getSystemInfoSync().platform
    const isIOS = platform === 'ios'
    this.setData({
      isIOS
    })
    this.updatePosition(0)
    let keyboardHeight = 0
    wx.onKeyboardHeightChange(res => {
      if (res.height === keyboardHeight) return
      const duration = res.height > 0 ? res.duration * 1000 : 0
      keyboardHeight = res.height
      setTimeout(() => {
        wx.pageScrollTo({
          scrollTop: 0,
          success() {
            that.updatePosition(keyboardHeight)
            that.editorCtx.scrollIntoView()
          }
        })
      }, duration)
    })
  },
  formSubmit: function(e) {
    var that = this;
    var formData = e.detail.value;
    formData["id"] = that.data.taskId;
    that.editorCtx.getContents({
      success: (res) => {
        console.log(res);
        if (res.text.length > 0 && res.html != "<p><br></p>") {
          formData["feedback"] = res.html;
          that.submitPost(formData);
        } else {
          wx.showModal({
            title: '请填写反馈内容',
          });
          return;
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提交失败',
        });
        console.log(err);
      }
    });
  },
  submitPost(formData) {
    var that = this;
    console.log(formData);
    wx.showToast({
      title: '正在提交',
      icon: 'loading',
      duration: 2000,
      mask: true,
    });
    var url = apiUrl.UrlXcTaskSubmit;
    http.ApiPost(url, formData, function(res) {
      if (res.code == 1) {
        wx.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000
        });
        wx.navigateBack();
      } else {
        wx.showModal({
          title: res.msg
        });
      }
    });
  },
  updatePosition(keyboardHeight) {
    const toolbarHeight = 50
    const {
      windowHeight,
      platform
    } = wx.getSystemInfoSync()
    let editorHeight = keyboardHeight > 0 ? (windowHeight - keyboardHeight - toolbarHeight) : windowHeight
    this.setData({
      editorHeight,
      keyboardHeight
    })
  },
  calNavigationBarAndStatusBar() {
    const systemInfo = wx.getSystemInfoSync()
    const {
      statusBarHeight,
      platform
    } = systemInfo
    const isIOS = platform === 'ios'
    const navigationBarHeight = isIOS ? 44 : 48
    return statusBarHeight + navigationBarHeight
  },
  onEditorReady() {
    const that = this
    wx.createSelectorQuery().select('#editor').context(function(res) {
      that.editorCtx = res.context;
      var detail = that.data.detail;
      if (detail&&detail.content) {
        that.editorCtx.setContents({
          html: detail.content,
          success: (res) => {
            console.log(res);
          },
          fail: (err) => {
            console.log(err);
          }
        });
      }
    }).exec()
  },
  blur() {
    this.editorCtx.blur()
  },
  format(e) {
    let {
      name,
      value
    } = e.target.dataset
    if (!name) return
    // console.log('format', name, value)
    this.editorCtx.format(name, value)
  },
  onStatusChange(e) {
    const formats = e.detail
    this.setData({
      formats
    })
  },
  insertDivider() {
    this.editorCtx.insertDivider({
      success: function() {
        console.log('insert divider success')
      }
    })
  },
  clear() {
    this.editorCtx.clear({
      success: function(res) {
        console.log("clear success")
      }
    })
  },
  removeFormat() {
    this.editorCtx.removeFormat()
  },
  insertDate() {
    const date = new Date()
    const formatDate = `${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`
    this.editorCtx.insertText({
      text: formatDate
    })
  },
  textIndent() {
    this.editorCtx.format('textIndent', '2em');
  },
  insertImage() {
    const that = this
    wx.chooseImage({
      count: 9,
      success: function(res) {
        for (let j = 0; j < res.tempFilePaths.length; ++j) {
          that.uploadImage(res.tempFilePaths[j])
        }
      }
    })
  },
  uploadImage: function(path) {
    var that = this
    that.showLoading();
    var postData = {};
    var user = wx.getStorageSync("user");
    if (user) {
      postData['appid'] = user.appid;
      postData['min_app'] = 1;
      wx.uploadFile({
        url: apiUrl.UrlUploadImg,
        filePath: path,
        name: 'file',
        formData: postData,
        success: function(res) {
          that.cancelLoading();
          var result = JSON.parse(res.data)
          // console.log(result);
          if (result.code == 1) {
            wx.hideToast();
            that.editorCtx.insertImage({
              src: result.data.url,
              width: '100%',
              success: function() {
                console.log('insert image success');
              }
            })
          } else {
            wx.showModal({
              title: result.msg
            });
          }
        },
        fail: function(err) {
          console.log(err);
          that.cancelLoading();
          wx.showModal({
            title: '上传出错！'
          });
        }
      })
    }
  },
  showLoading: function() {
    this.setData({
      showLoading: true
    })
  },
  cancelLoading: function() {
    this.setData({
      showLoading: false
    })
  },
})